package com.netcombine.freewill.lib;


public class Paging{
	
	private int page;
	private int total_cnt;
	private int block_page;	
	
	private int page_size;
	private int page_start;
	
	private int start_page;
	private int end_page;
	private int total_page;
	
	private String paging_script;
	
	public Paging(int page, int total_cnt, int page_size, int block_page, String paging_script){
		
		this.page = page;
		this.total_cnt = total_cnt;
		this.page_size = page_size;
		this.block_page = block_page;
		this.paging_script = paging_script;
		
		total_page = (total_cnt - 1) / page_size + 1;
		
		start_page = ((page - 1) / block_page) * block_page + 1;
		end_page = start_page + block_page - 1;
		
		if(total_page < end_page){
			
			end_page = total_page;
		}
		
		page_start = (page - 1) * page_size;
	}
	
	public int getPageSize(){
		
		return page_size;
	}
	
	public int getPageStart(){
		
		return page_start;
	}
	
	public int getTotalCnt(){
		
		return total_cnt;
	}
	
	private String getScript(int move_page){
		
		String script = "javascript:" + paging_script + "(" + move_page + ");";
		
		return script;
	}
	
	public String getPagingHtml(){
		
		int prev_page_num = (page > block_page) ? start_page - 1 : page;
		int next_page_num = ((end_page + 1) <= total_page) ? (end_page + 1) : page;
		
		String first_page = "<a class=\"go_pp\" href=\"" + getScript(1) + "\">처음</a>";
		String prev_page = "<a class=\"go_p\" href=\"" + getScript(prev_page_num) + "\">이전페이지</a>";
		
		String next_page = "<a class=\"go_f\" href=\"" + getScript(next_page_num) + "\">다음페이지</a>";
		String last_page = "<a class=\"go_ff\" href=\"" + getScript(total_page) + "\">마지막</a>";
		
		String page_info = "<p class=\"amount\">총<em>" + total_cnt + "</em>건 (<strong>" + page + "</strong> / " + total_page + ") </p>";
		
		// make paging html
		StringBuffer html = new StringBuffer();
		
		html.append("<div class=\"paging_area\">");
		html.append(page_info);
		html.append("<div class=\"paging\">");
		html.append(first_page);
		html.append(prev_page);
		
		html.append("<span class=\"num\">");
		
		for(int i=start_page; i<=end_page; i++){
			
			String now_page_class = (page == i) ? "class=\"on\"" : "";
			
			html.append("<a href=\"" + getScript(i) + "\" " + now_page_class + ">" + i +"</a>");
		}
		
		html.append("</span>");
		
		html.append(next_page);
		html.append(last_page);
		
		html.append("</div>");
		html.append("</div>");
		
		return html.toString();
	}
}
